package closure

/**
 * @ClassName Closure
 * @Description 闭包
 *  闭包是一个短的匿名代码块
 * @Author daoxuan
 * @create: 2019-09-16 13:04
 * @Version 1.0
 */

class Closure {
    //定义一个闭包作为参数的method
    def static Display(clob) {
        // This time the $param parameter gets replaced by the string "Inner"
        clob.call("Inner");
    }
    static void main(String[] args) {
      //
        println "闭包"+"--"*30
        def clos = {println "Hello World"}; //闭包

        clos.call();//标识符引用的代码块可以使用call语句执行


        println "形式参数"+"--"*30
        //
        def clos1 = {param->println "Hello ${param}"}; //param 形参  传参 ${param} 这种形式 引用
        clos1.call("World");
        println "--"*30
        //隐式单个参数  it Groovy中的关键字
        def clos2 = {println "Hello ${it}"};
        clos2.call("World");



        println "变量也可以使用在 闭包中"+"--"*30
        def str1 = "Hello";
        def clos3 = {param -> println "${str1} ${param}"}
        clos3.call("World");
        // We are now changing the value of the String str1 which is referenced in the closure
        str1 = "Welcome";
        clos3.call("World");

        //闭包也可以用作方法的参数

        println "闭包也可以用作方法的参数"+"--"*30
        def str11 = "Hello";
        def clos22 = { param -> println "${str11} ${param}" }
        this.Display(clos22)

        println "集合和字符串中的闭包"+"--"*30

        def lst = [11, 12, 13, 14]; //列表
        lst.each {s ->println s}

        println "--"*30
        def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] //映射闭包
        mp.each {println it}
        println "--"*30
        mp.each {println "${it.key} maps to: ${it.value}"}





    }
}
